﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using UFC.DBUtility;
using System.Xml;
using UFC.Common;

namespace MESQualityHistoryRecord
{
    public class SendSubmitIqsOrder
    {
        public void RunSubmitIqsOrder()
        {
            DataTable mainDT = GetSubmitIqsOrderData();
            foreach (DataRow row in mainDT.Rows)
            {
                var resQxml = CreateXmlForSubmitIqsOrder(row);
                LogHelp.WriteLog("理化试验委托单提交集成接口-推送XML:" + resQxml);
                NewMesToQms.unifiedFunApi mtq = new NewMesToQms.unifiedFunApi();
                var resPxml = mtq.mesToQmsAPI(resQxml);
                LogHelp.WriteLog("理化试验委托单提交集成接口-返回XML:" + resPxml);
                if (!string.IsNullOrWhiteSpace(resPxml))
                {
                    XmlDocument myxml = new XmlDocument();
                    myxml.LoadXml(resPxml);
                    string xml = myxml.SelectSingleNode("RespMsg/document").InnerText;
                    myxml.LoadXml(xml);
                    string success = myxml.SelectSingleNode("TETTYP/RTYPE").InnerText;//
                    string message = myxml.SelectSingleNode("TETTYP/RTMSG").InnerText;//
                    Dictionary<string, string> recordPara = new Dictionary<string, string>() { 
                        {"ParentId",row["entrustID"].ToString ()},{"RecordType","QMS_SubmitIqsOrder"},
                        {"ContainerID",row["ContainerID"].ToString ()},{"ContainerName",row["ContainerName"].ToString ()},
                        {"ProductName",row["ProductName"].ToString ()},{"WorkflowStepName",""},
                        {"SendXml",resQxml},{"ResXml",resPxml}
                    };
                    if (success == "S")
                    {
                        recordPara.Add("IsSuccess", "0");//成功
                        UpdateEntrusName(row, message);
                    }
                    else
                    {
                        recordPara.Add("IsSuccess", "1");//失败                    
                    }
                    OracleDAL.InserOtherSystemRecord(recordPara);
                }

            }
        }
        /// <summary>
        /// 理化试验项目-主表数据
        /// </summary>
        /// <returns></returns>
        public DataTable GetSubmitIqsOrderData()
        {
            string strSql = @"SELECT e.ENTRUSTNAME ,e.ENTRUSTMEASUREMENTID entrustID,f.factoryName,u.ATTRIBUTEVALUE factoryCode,p2.PRODUCTNAME,p.DESCRIPTION productDesc
                    ,c.CONTAINERNAME partBatchNo,e.ENTRUSTQTY qty,p.materialTrademark,'/'testType,m.MATERIALTYPENAME  materialType,p.materialName,e.specification,e.batchNO
                    ,'LY19' entrustType,e2.employeeName,e2.FULLNAME employeeDesc--DECODE(e.ENTRUSCHECKTYPE,'1','LY09','2','LY04','3','LY05','LY19')
                    ,c.FAMILYLISTNAMES productFamily,s.specNO,p.materialSpecification,e.ENTRUSTNAME testItemOrRequirement,e.EntrustNote note
                    ,e3.EMPLOYEENAME checkerName,e3.FULLNAME checkerDesc,to_char(e.entrustDate,'yyyy-MM-dd hh24:mi:ss') entrustDate,'/'sendEmployeeName,to_char(sysdate,'yyyy-MM-dd hh24:mi:ss') sendDate,e.CONTAINERID,c.CONTAINERNAME
                    FROM EntrustMeasurement  e 
                    LEFT JOIN FACTORY f ON f.FACTORYID =e.FACTORYID 
                    LEFT JOIN Userattribute u ON u.PARENTID =f.FACTORYID AND u.USERATTRIBUTENAME ='理化分厂代码'
                    LEFT JOIN PRODUCT p ON p.PRODUCTID =e.PRODUCTID 
                    LEFT JOIN PRODUCTBASE p2 ON p2.PRODUCTBASEID =p.PRODUCTBASEID
                    LEFT JOIN MaterialType m ON m.MATERIALTYPEID =p.MATERIALTYPEID 
                    LEFT JOIN CONTAINERCURRENTINFO c ON c.CONTAINERID =e.CONTAINERID 
                    LEFT JOIN EMPLOYEE e2 ON e2.EMPLOYEEID =e.ENTRUSTORID 
                    LEFT JOIN EMPLOYEE e3 ON e3.EMPLOYEEID =e.TREATEMPLOYEEID 
                    LEFT JOIN WORKFLOWSTEP w  ON w.WORKFLOWSTEPID =e.WORKFLOWSTEPID 
                    LEFT JOIN Workflow wf ON w.workflowid = wf.workflowid
					LEFT JOIN specbase sb_ ON sb_.specbaseid = w.specbaseid
					LEFT JOIN spec s ON s.specid = NVL(sb_.revofrcdid,w.specid)
                    left join WritetoOtherSystem ws on ws.parentid=e.ENTRUSTMEASUREMENTID and ws.recordtype='QMS_SubmitIqsOrder'
                    WHERE nvl(e.ISPHY,0)=1 and ws.parentid is null and rownum<500";
            return OracleHelper.QueryTable(strSql, null);
        }
        /// <summary>
        /// 理化试验项目-明细数据
        /// </summary>
        /// <param name="mainID"></param>
        /// <returns></returns>
        public DataTable GetSubmitIqsOrderDetailData(string mainID)
        {
            string strSql = @"SELECT e.DETAILNO testNo,e.CHECKPOINTNAME test_Item,e.CHECKPOINTNOTE, '' test_Depe,'0'smaple_Qty,''extend10,''remark
                        FROM EntrustMeasurementDetail e WHERE e.ENTRUSTMEASUREMENTID ='" + mainID + "'";
            return OracleHelper.QueryTable(strSql, null);
        }
        /// <summary>
        /// 理化试验项目-xml组装
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        public string CreateXmlForSubmitIqsOrder(DataRow row)
        {
            //获取委托理化试验项目
            DataTable TestItemsList = GetSubmitIqsOrderDetailData(row["entrustID"].ToString());
            if (row["factoryName"].ToString().Equals("热表厂")&&!row["note"].ToString().Contains("批次")) 
            {
                try { 
                     DataTable dt = OracleHelper.QueryTable(string.Format(@"select c2.containername from containersubcontainer c 
                            left join containercurrentinfo c2 on c2.containerid =c.containerid where c.subcontainerid='{0}'", row["containerid"]),null);
                     if (dt.Rows.Count > 0) {
                         row["note"] = row["note"].ToString() + "  批次号：" + dt.Rows[0]["containername"].ToString().Split('/')[1] + "/" + row["partBatchNo"].ToString().Split('/')[1];
                     }
                
                }catch(Exception ex){}
            }
            #region MyRegion
            XmlDocument doc = new XmlDocument();
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
            XmlNode ReqNode = doc.CreateElement("ReqMsg");
            XmlNode headerNode = doc.CreateElement("header");
            XmlNode senderNode = doc.CreateElement("sendSysName");
            senderNode.InnerText = "APP_MES";
            XmlNode rcvNode = doc.CreateElement("rcvSysName");
            rcvNode.InnerText = "APP_QMS";
            XmlNode extNode = doc.CreateElement("extConfig");
            extNode.AppendChild(doc.CreateElement("isReTry"));
            extNode.LastChild.InnerText = "false";
            extNode.AppendChild(doc.CreateElement("FunName"));
            extNode.LastChild.InnerText = "MES_Send_Service";
            headerNode.AppendChild(senderNode);
            headerNode.AppendChild(rcvNode);
            headerNode.AppendChild(extNode);
            ReqNode.AppendChild(headerNode);

            XmlNode root = doc.CreateElement("root");
            XmlNode qmsFun = doc.CreateElement("qmsFunName");
            qmsFun.InnerText = "submitIqsOrder";
            root.AppendChild(qmsFun);

            XmlNode documentNode = doc.CreateElement("document");
            ReqNode.AppendChild(documentNode);

            XmlNode qmsDocument = doc.CreateElement("qmsDocument");//具体业务内容
            #endregion

            #region MyRegion
            string[] mainHeaderText = {"entrustName","entrustID","factoryCode","factoryName","productName","productDesc",
                                     "partBatchNo","qty","materialTrademark","testType","materialType","materialName",
                                     "specification","batchNO","entrustType","employeeName","employeeDesc",
                                     "productFamily","specNO","materialSpecification","testItemOrRequirement","note",
                                     "checkerName","checkerDesc","entrustDate","sendEmployeeName","sendDate" };
            foreach (string ht in mainHeaderText)
            {
                XmlNode mainData = doc.CreateElement(ht);
                mainData.InnerText = row[ht].ToString();
                qmsDocument.AppendChild(mainData);
            }
            #endregion

            #region testItemsList 理化试验项目
            XmlNode ItemsListNode = doc.CreateElement("testItemsList");//
            string[] detail = { "testNo", "test_Item", "test_Depe", "smaple_Qty", "extend10", "remark", };
            foreach (DataRow drow in TestItemsList.Rows)
            {
                if (!string.IsNullOrWhiteSpace(drow["test_Item"].ToString()))//检测项为空，不传
                {
                    XmlNode TestItemNode = doc.CreateElement("testItem");//
                    foreach (string ht in detail)
                    {
                        XmlNode dData = doc.CreateElement(ht);
                        dData.InnerText = drow[ht].ToString();
                        TestItemNode.AppendChild(dData);
                    }
                    ItemsListNode.AppendChild(TestItemNode);
                }
            }
            qmsDocument.AppendChild(ItemsListNode);
            #endregion

            root.AppendChild(qmsDocument);
            documentNode.AppendChild(doc.CreateCDataSection("<root>" + root.InnerXml + "</root>"));
            doc.AppendChild(ReqNode);
            return doc.InnerXml;

        }
        /// <summary>
        /// 更新请托单号
        /// </summary>
        /// <param name="row"></param>
        /// <param name="message"></param>
        public void UpdateEntrusName(DataRow row, string message)
        {
            try
            {
                var updateSQL = @"update EntrustMeasurement set QMSENTRUSTNAME='{0}' where ENTRUSTMEASUREMENTID='{1}'";
                OracleHelper.ExecuteSql(string.Format(updateSQL, message, row["entrustID"]));
            }
            catch (Exception ex)
            {
                LogHelp.WriteLog("理化试验委托单提交集成接口-返回更新请托单号失败:" + ex.Message);
            }
        }
    }
}
